<template>
	<div class="container">
		<el-form ref="loginForm" :model="formData" :rules="rules" label-width="auto" hide-required-asterisk>
			<h1>十方智育 - 后台登录</h1>
			<el-form-item label="用户名" prop="username">
				<el-input size="large" v-model="formData.username" placeholder="请输入账号" :prefix-icon="Avatar"></el-input>
			</el-form-item>
			<el-form-item label="密码" prop="password">
				<el-input size="large" v-model="formData.password" placeholder="请输入密码" type="password" show-password
					:prefix-icon="Lock">
				</el-input>
			</el-form-item>
			<el-form-item style="margin-left: 54px;">
				<el-button type="primary" @click="login(loginForm)">登录</el-button>
				<el-button @click="resetForm(loginForm)">取消</el-button>
			</el-form-item>
		</el-form>
	</div>
</template>

<script lang='ts' setup>
	import { useCounterStore } from '../stores/counter';
	import { getCurrentInstance,reactive,ref } from 'vue'
	import type { FormInstance,FormRules } from 'element-plus'
	import { ElMessage } from 'element-plus'
	import { Avatar,Lock } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
const counter = useCounterStore();
	const loginForm = ref <FormInstance>()
	const formData = reactive({
		username: '',
		password: ''
	})
	const rules = reactive({
		username: [
			{required: true,message: '请输入账号',trigger: 'blur'},
			{min: 4,max: 20,message: '长度在 4 到 20 个字符',trigger: 'blur'}
		],
		password: [
			{required: true,message: '请输入密码',trigger: 'blur'},
			{min: 6,message: '长度至少 6 个字符',trigger: 'blur'}
		]
	})
	const axios = getCurrentInstance().appContext.config.globalProperties.axios;
	const router=useRouter();
	const login = async (formEl) => {
		if (!formEl) return
		await formEl.validate((valid, fields) => {
			if (valid) {
				console.log(formData.username, formData.password)
				axios.get(
					`login?username=${formData.username}&userpwd=${formData.password}&source=1`,
				).then(resp => {
					console.log(resp.data);
					if(resp.code==200){
						//存到sessionStorage里
						ElMessage.success('登陆成功')
						counter.userInfo=resp.data
						// console.log(counter.userInfo);
						router.replace('/index')
					}else{
						ElMessage.error(resp.data)
					}
				})
			} else {
				ElMessage.error('请输入正确的账号和密码')
			}
		})
	}
	const resetForm = (formEl) => {
		if (!formEl) return
		formEl.resetFields()
	}
</script>

<style scoped>
	.container {
		height: 100vh;
		background: url('../assets/login_bg.jpg') no-repeat;
		background-size: 100%;
		overflow: hidden;
		position: relative;
	}

	.el-form {
		width: 500px;
		/* margin: 150px auto; */
		position: absolute;
		left: 50%;
		top: 50%;
		transform: translate(-50%,-50%);
		padding: 30px 50px;
		border-radius: 10px;
		box-shadow: 0 8px 16px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
		background: rgba(255, 255, 255, 0.8);
	}

	h1 {
		text-align: center;
	}
</style>